package com.gxs.ea.fileporta.data.services;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import com.gxs.ea.fileportal.data.repositories.CompanyRepository;
import com.gxs.ea.fileportal.model.persisted.Company;

@Service("companyService")
public class CompanyServiceImpl implements CompanyService 
{
	public static final String COLLECTION_NAME = "company";
	
	@Autowired
    private MongoTemplate mongoTemplate;
	@Autowired
	private CompanyRepository companyRepository;

	@Override
	public Company saveCompany(Company company) 
	{
		Company existing = companyRepository.findByCompanyCode(company.getCompanyCode());
		
		if(existing == null)
		{
			company.setId(UUID.randomUUID().toString());
			return this.companyRepository.save(company);
		}
		else
		{
			throw new RuntimeException("Duplicate Company Code: Comapany wiht code " + company.getCompanyCode() + " already exists");
		}
	}

	@Override
	public List<Company> listCompanies() 
	{
		 return this.companyRepository.findAll();	
	}

	@Override
	public void deleteCompany(Company company) 
	{
		this.companyRepository.delete(company);		
	}

	@Override
	public void updateCompany(Company company) 
	{
		this.companyRepository.save(company);		
	}

	@Override
	public Company findById(String id) 
	{
		return this.companyRepository.findOne(id);
	}

	@Override
	public Company findByCompanyCode(String companyCode) 
	{
		return this.companyRepository.findByCompanyCode(companyCode);
	}
}
